package lab.dexter.bbsreader.managers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lab.dexter.bbsreader.ListManager;
import lab.dexter.bbsreader.NewSMTHHttpClient;
import lab.dexter.bbsreader.R;
import lab.dexter.bbsreader.utils.ImageGallery;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class PostManager extends ListManager {
	
	public static final String PARAM_BOARD = "BOARD";
	public static final String PARAM_INITIAL_ID = "ID";
	
	private String nextTarget;
	private String board;
	private String id;
	
	private Post post;
	
	private Pattern pattern_content;
	private Pattern pattern_author;
	private Pattern pattern_page;
	private Pattern pattern_id;
	private Pattern pattern_head_id;
	private Pattern pattern_image;
	
	private final String regexp_content = "<div align=\"left\" class=\"ctt\">(.*?)</div>";
	private final String regexp_author = "信人: (.*?) \\(";
	private final String regexp_page = "=([0-9]+)\">回版面";
	private final String regexp_id = "reid=([0-9]+)\"";
	private final String regexp_head_id = "id=([0-9]+)\">溯源";
	private final String regexp_image = "<li><a\\s+href='(.+?(\\.jpg)|(\\.png)|(\\.jpeg)|(\\.gif))'\\s+target='_blank'>(.+?)</a></li>";
	
	private boolean bottomPanelEnabled;
	

	private class Post {
		
		public String id;
		public String author;
		public String page;
		public String content;
		public String head;
		
		public ArrayList<String> imagePathList;
		public ArrayList<String> imageNameList;
		
		public Post() {
			imagePathList = new ArrayList<String>();
			imageNameList = new ArrayList<String>();
		}
		
		public void addImage(String path, String filename) {
			imagePathList.add(path);
			imageNameList.add(filename);
		}
	}
		
	public PostManager(Context context, Intent intent) {
		super(context, intent);
		board = intent.getStringExtra(PARAM_BOARD);
		id = intent.getStringExtra(PARAM_INITIAL_ID);
		
		pattern_content = Pattern.compile(regexp_content);
		pattern_author = Pattern.compile(regexp_author);
		pattern_page = Pattern.compile(regexp_page);
		pattern_id = Pattern.compile(regexp_id);
		pattern_head_id = Pattern.compile(regexp_head_id);
		pattern_image = Pattern.compile(regexp_image);
		
		// different
		post = new Post();
		
		nextTarget = "http://www.newsmth.net/atomic2.php?act=article&board=" + board + "&id=" + id;
		
		bottomPanelEnabled = false;
	}

	@Override
	public boolean onItemClick(int position) {
		assert(position > 0);
		Intent intent = new Intent(mContext, ImageGallery.class);
		intent.putStringArrayListExtra(ImageGallery.PARAM_PATH_LIST, post.imagePathList);
		intent.putStringArrayListExtra(ImageGallery.PARAM_NAME_LIST, post.imageNameList);
		mContext.startActivity(intent);
		return false;
	}

	@Override
	public int update() {
		try {
			NewSMTHHttpClient.getClient().fetchData(nextTarget, this);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	public void dataProcessor(HttpEntity entity) {
		try {
			// stupid server massed up the charset header, so we do the decoding manually
			//content = EntityUtils.toString(entity);
			BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
			StringBuilder builder = new StringBuilder();
			String line = null;
			while((line = reader.readLine()) != null) {
				builder.append(line);
			}
			String content = builder.toString();
			if(content.length() > 10) {
			
				Matcher matcher = pattern_content.matcher(content);
				if(!matcher.find()) {
					return;
				}
				post.content = Html.fromHtml(matcher.group(1)).toString();
				
				matcher = pattern_author.matcher(post.content);
				if(matcher.find()) {
					post.author = matcher.group(1);
				}
				
				matcher = pattern_page.matcher(content);
				if(matcher.find()) {
					post.page = matcher.group(1);
				}
				
				matcher = pattern_id.matcher(content);
				matcher.find();
				post.id = matcher.group(1);
				
				matcher = pattern_head_id.matcher(content);
				matcher.find();
				post.head = matcher.group(1);
				bottomPanelEnabled = true;
				
				// Handle pictures
				matcher = pattern_image.matcher(content);
				while(matcher.find()) {
					post.addImage(matcher.group(1), matcher.group(6));
					//Log.v("MATCH", matcher.group(1) + " " + matcher.group(6));
				}
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public boolean areAllItemsEnabled() {
		return false;
	}

	public boolean isEnabled(int position) {
		if(position > 0) {
			return true;
		}
		return false;
	}

	public int getCount() {
		if(post.imagePathList.size() > 0) {
			return 2;
		}
		return 1;
	}

	public Object getItem(int position) {
		return post;
	}

	public long getItemId(int position) {
		return position;
	}

	public int getItemViewType(int position) {
		if(position > 0) {
			return 1;
		}
		return 0;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		
		if(position > 0) {
			// there are attached images
			if(view == null) {
				LayoutInflater vi = (LayoutInflater)(mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
				view = vi.inflate(android.R.layout.simple_list_item_1, null);
			}
			TextView tv = (TextView)view.findViewById(android.R.id.text1);
			tv.setText("View Attachments");
			return view;
		}
		
		if(view == null) {
			LayoutInflater vi = (LayoutInflater)(mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE));
            view = vi.inflate(R.layout.post_view, null);
		}
		if(post != null && post.id != null) {
			TextView tv = (TextView)view.findViewById(R.id.post);
			tv.setText(post.content);
		}
		return view;
	}

	public int getViewTypeCount() {
		return 2;
	}
	
	@Override
	public boolean hasBottomPanel() {
		return true;
	}
	
	@Override
	public int getBottomPanelResource() {
		return R.layout.post_bottom_panel;
	}
	
	@Override
	public int[] getBottomPanelMembers() {
		int[] array = {R.id.button_first, R.id.button_next, R.id.button_prev, R.id.button_topic_next, R.id.button_topic_prev};
		return array;
	}
	
	@Override
	public boolean onClickOnBottomPanel(View view) {
		if(!bottomPanelEnabled) {
			// avoid multiple click
			return false;
		}
		int id = ((Button)view).getId();
		Log.w("Bottom Panel", Integer.toString(id));
		String action = "";
		switch(id) {
		case R.id.button_first:
			post.id = post.head;
			break;
		case R.id.button_next:
			action = "&p=n";
			break;
		case R.id.button_prev:
			action = "&p=p";
			break;
		case R.id.button_topic_next:
			action = "&p=tn";
			break;
		case R.id.button_topic_prev:
			action = "&p=tp";
			break;
		default:
			return false;
		}
		nextTarget = "http://www.newsmth.net/atomic2.php?act=article&board=" + board + "&id=" + post.id + action;
		this.id = post.id;
		post.id = null;
		bottomPanelEnabled = false;
		return true;
	}
	
	@Override
	public String getTitleSuffix() {
		return "阅读文章";
	}
}
